package com.bookstore.test;

import com.bookstore.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo01 {
    @Test
    public void test01() {
        //javabean和json的互转
        User user = new User();
        user.setId(1L);
        user.setUsername("admin");
        user.setPassword("123");

        //java对象转成JSON字符串
        Gson gson = new Gson();
        String s = gson.toJson(user);
        System.out.println(s);
        //JSON字符串 还原成java对象
        User user1 = gson.fromJson(s, User.class);
        System.out.println(user1);
    }

    @Test
    public void test02() {
        List<User> users = new ArrayList<>();
        User user1 = new User();
        user1.setId(1L);
        user1.setUsername("admin");
        user1.setPassword("123");
        User user2 = new User();
        user2.setId(2L);
        user2.setUsername("admin");
        user2.setPassword("123");
        User user3 = new User();
        user3.setId(3L);
        user3.setUsername("admin");
        user3.setPassword("123");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        System.out.println(users);

        //List对象转成JSON字符串
        Gson gson = new Gson();
        String s = gson.toJson(users);
        System.out.println(s);
        //JSON字符串 还原成List对象
        List<User> o = gson.fromJson(s, new TypeToken<List<User>>() {
        }.getType());
        System.out.println(o);
    }

    @Test
    public void test03() {
        User user1 = new User();
        user1.setId(1L);
        user1.setUsername("admin");
        user1.setPassword("123");
        User user2 = new User();
        user2.setId(2L);
        user2.setUsername("admin");
        user2.setPassword("123");
        User user3 = new User();
        user3.setId(3L);
        user3.setUsername("admin");
        user3.setPassword("123");
        Map<Integer, User> map = new HashMap<>();
        map.put(1, user1);
        map.put(2, user2);
        map.put(3, user3);

        //Map对象转成JSON字符串
        Gson gson = new Gson();
        String s = gson.toJson(map);
        System.out.println(s);
        //JSON字符串 还原成Map对象
        Map<Integer, User> o = gson.fromJson(s, new TypeToken<Map<Integer, User>>() {
        }.getType());
        System.out.println(o);
    }
}
